package com.skyline.energy.utils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于替换SQL中的通用表名的工具类
 * 
 * @author wuqh
 * 
 */
public final class SqlFormatter {
	private static final Map<String, String> FORMATTED_SQL = new HashMap<String, String>();

	private SqlFormatter() {
	}

	/**
	 * 按照MessageFormat的规则替换SQL中的通用表名
	 * 
	 * @param sqlNeedFormat
	 * @param tableNames
	 * @return
	 */
	public static String formatSql(String sqlNeedFormat, String[] tableNames) {
		String keyStr = buildKey(sqlNeedFormat, tableNames);
		String sql = FORMATTED_SQL.get(keyStr);
		if (sql == null) {
			sql = doFormat(sqlNeedFormat, tableNames);
			FORMATTED_SQL.put(keyStr, sql);
		}
		return sql;

	}

	private static String doFormat(String sqlNeedFormat, String[] tableNames) {
		MessageFormat format = new MessageFormat(sqlNeedFormat);
		return format.format(tableNames);
	}

	private static String buildKey(String sqlNeedFormat, String[] tableNames) {
		StringBuilder key = new StringBuilder();
		for (String tableName : tableNames) {
			key.append(tableName);
		}
		key.append(sqlNeedFormat);
		String keyStr = key.toString();
		return keyStr;
	}
}
